package com.atguigu.gmall.payment.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.atguigu.gmall.model.enums.PaymentStatus;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.mapper.PaymentInfoMapper;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;


@Service
public class AlipayServiceImpl implements AlipayService {

    @Autowired
    private AlipayClient alipayClient;
    @Autowired
    private OrderFeignClient orderFeignClient;
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private PaymentInfoMapper paymentInfoMapper;

    //生成二维码
    @Override
    public String createAliPay(Long orderId) {
        OrderInfo orderInfo = this.orderFeignClient.getOrderInfo(orderId);
        String form = "";
        //保存交易记录
        this.paymentService.savePaymentInfo(orderInfo, PaymentType.ALIPAY.name());
        //判断订单状态
        if ("CLOSED".equals(orderInfo.getOrderStatus())||"PAID".equals(orderInfo.getOrderStatus())){
            return "订单已支付或已关闭";
        }
        AlipayTradePagePayRequest alipayRequest =  new  AlipayTradePagePayRequest();
        //设置同步回调
        alipayRequest.setReturnUrl(AlipayConfig.return_payment_url);
        //设置异步回调
        alipayRequest.setNotifyUrl(AlipayConfig.notify_payment_url);
        JSONObject jsonObject = new JSONObject();
        //out_trade_no 商户订单号
        jsonObject.put("out_trade_no",orderInfo.getOutTradeNo());
        //total_amount 订单总金额
        jsonObject.put("total_amount","0.01");
        //subject
        jsonObject.put("subject",orderInfo.getTradeBody());
        //product_code
        jsonObject.put("product_code","FAST_INSTANT_TRADE_PAY");//电脑
        //jsonObject.put("product_code", "QUICK_WAP_WAY");//手机
        //二维码过期时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //时间计算
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,10);
        jsonObject.put("time_expire",simpleDateFormat.format(calendar.getTime()));
        alipayRequest.setBizContent(jsonObject.toJSONString());
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return form;
    }

    //退款接口
    @Override
    public Boolean refund(Long orderId) {
        OrderInfo orderInfo = this.orderFeignClient.getOrderInfo(orderId);
        if ("CLOSED".equals(orderInfo.getOrderStatus())){
            return false;
        }

        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no",orderInfo.getOutTradeNo());
        bizContent.put("refund_amount",0.01);
        bizContent.put("refund_reason","七天无理由");
        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if (response.isSuccess()){
            //修改交易状态
            PaymentInfo paymentInfo = new PaymentInfo();
            paymentInfo.setPaymentStatus(PaymentStatus.CLOSED.name());
            paymentInfo.setUpdateTime(new Date());

            this.paymentService.updatePaymentInfoStatus(orderInfo.getOutTradeNo(),PaymentType.ALIPAY.name(),paymentInfo);
            System.out.println("调用成功");
            return true;
        }else{
            System.out.println("调用失败");
            return false;
        }
    }

    ////关闭支付宝交易记录
    @Override
    public Boolean closePay(Long orderId) {
        OrderInfo orderInfo = this.orderFeignClient.getOrderInfo(orderId);
        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        request.setBizContent(bizContent.toString());
        AlipayTradeCloseResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
            return true;
        } else {
            System.out.println("调用失败");
            return false;
        }
    }

    //查询支付宝交易记录
    @SneakyThrows
    @Override
    public Boolean checkPayment(Long orderId) {
        //根据orderId获取OrderInfo
        OrderInfo orderInfo = this.orderFeignClient.getOrderInfo(orderId);
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        HashMap<String, Object> map = new HashMap<>();
        map.put("out_trade_no",orderInfo.getOutTradeNo());
        request.setBizContent(JSON.toJSONString(map));
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        if (response.isSuccess()){
            System.out.println("调用成功"+response.getTradeStatus());
            return true;
        }else{
            System.out.println("调用失败"+response.getTradeStatus());
            return false;
        }
    }
}
